import logging
from google.appengine.api import users

import datamodel
from post import *

def writepage(self, threads, reply_to=None, doreturn=False, cached=False, pagenum=None):  
  pages_text = ''
  cachedat = None
  
  if reply_to is None:
    pages_text = pages_text + '<td>'

    pages = int(math.ceil(float(totalthreads()) / 10))
    
    if pagenum == 0:
      pages_text = pages_text + 'Previous'
    else:
      previous = str(pagenum - 1)
      if previous == '0':
        previous = ''
      else:
        previous = previous + '.html'
      pages_text = pages_text + '<form method="get" action="/' + previous + '"><input value="Previous" type="submit"></form>'

    pages_text += '</td><td>'

    for i in xrange(0, pages):
      if i == pagenum:
        pages_text = pages_text + '[' + str(i) + '] '
      else:
        if i == 0:
          pages_text = pages_text + '[<a href="/">' + str(i) + '</a>] '
        else:
          pages_text = pages_text + '[<a href="/' + str(i) + '.html">' + str(i) + '</a>] '
        
    pages_text = pages_text + '</td><td>'

    next = (pagenum + 1)
    if next == 10 or next == pages:
      pages_text = pages_text + 'Next</td>'
    else:
      pages_text = pages_text + '<form method="get" action="/' + str(next) + '.html"><input value="Next" type="submit"></form></td>'

  if cached:
    cachedat = datetime.now().strftime("%y/%m/%d %H:%M:%S")

  if reply_to is None:
    ispage = 'true'
  else:
    ispage = 'false'
  template_values = {
    'threads': threads,
    'replythread': reply_to,
    'pages': pages_text,
    'cached': cachedat,
    'is_page': ispage,
    }
  
  return self.generate('index.html', template_values, doreturn)

def fetchpage(self, page_name, pagenum=0):
  # If ?admin is in the URL, and the current user is an administrator, don't give them a cached page
  if users.is_current_user_admin() and self.request.get('admin', None) is not None:
    Settings._ADMINISTRATOR_VIEW = True
    
  if page_name == 'front':
    if pagenum > 0:
      page_name += str(pagenum)

    page = datamodel.Page.all().filter('identifier = ', page_name).get()
      
    if page and not Settings._ADMINISTRATOR_VIEW:
      page_contents = page.contents
    else:
      #try:
      page_contents = recachepage(self, 'front', pagenum)
      #except:
      #  return self.error('Invalid thread ID supplied.')
  else:
    page = datamodel.Page.all().filter('identifier = ', page_name).get()
    if page and not Settings._ADMINISTRATOR_VIEW:
      page_contents = page.contents
    else:
      #try:
      page_contents = recachepage(self, page_name)
      #except:
      #  return self.error('Invalid thread ID supplied.')

  self.response.out.write(page_contents)

def recachepage(self, page_name, pagenum=0):
  if page_name == 'front':
    if pagenum > 0:
      page_name += str(pagenum)
      
    page = datamodel.Page.all().filter('identifier = ', page_name).get()
    if not page:
      page = datamodel.Page(identifier=page_name)

    try:
      threads = getposts(self, None, (pagenum * 10))
    except:
      raise
    page_contents = writepage(self, threads, None, True, True, pagenum)
  else:
    post = datamodel.Post.get(page_name)
    if post:
      if post.parentid is not None:
        return self.error('Error: Invalid thread ID.')
    
    page = datamodel.Page.all().filter('identifier = ', page_name).get()
    if not page:
      page = datamodel.Page(identifier=page_name)
    
    threads = getposts(self, page_name, 0)
    page_contents = writepage(self, threads, page_name, True, True)

  if not Settings._ADMINISTRATOR_VIEW:
    page.contents = page_contents
    page.put()

  return page_contents

def threadupdated(self, thread_key=None):
  thread_key = str(thread_key)
  logging.debug('THREADUPDATED: Thread ' + thread_key + ' updated')
  
  clearfrontpages(self)
  if thread_key:
    clearpage(thread_key)

def clearpage(page_name):
  page_name = str(page_name)
  logging.debug('CLEARPAGE: Clearing page ' + page_name)
  
  page = datamodel.Page.all().filter('identifier = ', page_name).get()
  if page:
    page.delete()
    
    logging.debug('CLEARPAGE: Cleared page ' + page_name)

def clearfrontpages(self):
  clearpage('catalog')
  clearpage('front')
  [clearpage(('front' + str(i))) for i in xrange(1, 10)]

def totalthreads():
  total_threads = datamodel.Post.all().filter('parentid = ', None)
  return total_threads.count()
